#include "TcpServer.hpp"

// ./client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "instruction error" << std::endl;
        exit(err);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // create socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "tcp socket create fail" << std::endl;
        exit(fail);
    }
    std::cout << "tcp socket create success" << std::endl;

    // connect
    sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(port);
    client_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    int connect_n = connect(sockfd, (struct sockaddr *)&client_addr, sizeof(client_addr));
    if (connect_n < 0)
    {
        std::cout << "connect socket fail" << std::endl;
        exit(fail);
    }

    while (true)
    {
        std::cout << "Enter Message #";
        std::string message;
        std::getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());

        char echo_message[SIZE] = {0};
        int read_n = read(sockfd, echo_message, sizeof(echo_message) - 1);
        if (read_n > 0)
        {
            echo_message[read_n] = 0;
            std::cout << echo_message << std::endl;
        }
        else if (read_n == 0)
        {
            std::cout << "read end" << std::endl;
            exit(success);
        }
        else 
        {
            std::cout << "read fail" << std::endl;
            exit(fail);
        }
    }

    close(sockfd);
    return 0;
}